function showPrompt(prompt) {
    try {
        const tipDom = document.getElementsByClassName('toast-body')[0];
        tipDom && (tipDom.textContent = prompt);
        document.getElementsByClassName('toast')[0].style.opacity = 1;
        setTimeout(() => {
            hideToast();
        }, 5000);
    } catch (error) {
        console.error(error)
    }
}

function hideToast() {
    try {
        document.getElementsByClassName('toast')[0].style.opacity = 0;
    } catch (error) {
        console.error(error)
    }
}

const validators = {
    1: (formProps, form) => {
        if (formProps.prompt == null || formProps.prompt == '') {
            showPrompt('[描述画面的提示词信息] 不能为空!');
            return false;
        }
        return true;
    }, 2: (formProps, form) => {
        if (formProps.prompt == null || formProps.prompt == '') {
            showPrompt('[涂鸦内容描述] 不能为空!');
            return false;
        }
        var canvas = document.getElementById('drawingCanvas');
        if (window.blankCanvasData === canvas.toDataURL()) {
            showPrompt('请先进行涂鸦后再提交!');
            return false;
        }
        formProps.imageData = canvas.toDataURL();
        return true;
    }, 3: (formProps, form) => {
        if (formProps.image == null || formProps.image == '' || formProps.image.size === 0) {
            showPrompt('图片不能为空!');
            return false;
        }
        if (formProps.image.size >= 10 * 1024 * 1024) {
            showPrompt('图片不能超过10MB!');
            return false;
        }
        return true;
    }, 4: (formProps, form) => {
        if (formProps.templateImage.size === 0) {
            showPrompt('[自定义风格模板]未上传!');
            return false;
        }
        if (formProps.templateImage.size >= 5 * 1024 * 1024) {
            showPrompt('[自定义风格模板]不能超过5MB!');
            return false;
        }
        let userImageList = [];
        if (form.userImageList instanceof RadioNodeList) {
            userImageList = form.userImageList;
        } else {
            userImageList.push(form.userImageList);
        }
        for (let file of userImageList) {
            if (file.files == null || file.files[0] == null || file.files[0].size === 0) {
                showPrompt('[用户正脸单人照]未上传!');
                return false;
            }
            if (file.files[0].size >= 3 * 1024 * 1024) {
                showPrompt('[用户正脸单人照]不能超过3MB!');
                return false;
            }
        }
        return true;
    },
};

function callback(data, index) {
    // 成功
    if (data.taskStatus === 'SUCCEEDED') {
        let element = document.getElementById('result-' + index);
        element.innerHTML = '';
        data.results.forEach((item) => {
            const img = document.createElement('img');
            img.src = item.url;
            img.style.cursor = 'pointer';
            img.alt = '点击查看大图';
            element.appendChild(img);
            img.addEventListener('click', function () {
                // 获取大图的URL
                var largeSrc = this.getAttribute('src');
                // 设置大图URL到模态框中的<img>元素
                document.getElementById('largeImage').src = largeSrc;
                // 显示模态框
                var imageModal = document.getElementById('imageModal');
                imageModal.style.display = 'flex';
            });
        });
        document.getElementById('tr-' + index).style.display = '';
        hideLoading();
        return;
    }
    // 继续查结果
    if (['RUNNING', 'PENDING'].includes(data.taskStatus)) {
        fetch('api/task-result?taskId=' + data.taskId)
            .then(response => response.json())
            .then(data => {
                console.log(data);
                if (data.success !== true) {
                    hideLoading();
                    showPrompt(data.message || '调用失败，请重试!');
                    return;
                }
                setTimeout(() => {
                    callback(data.data, index);
                }, 3000);
            })
            .catch(error => {
                console.log(error);
                hideLoading();
                showPrompt('请求失败，请重试!');
            });
        return;
    }
    hideLoading();
    showPrompt('任务失败或状态未知, 请重试! code=' + data.code + ', msg=' + data.message);
}

function submitForm(index) {
    const form = document.getElementById('form-' + index);
    const formProps = Object.fromEntries(new FormData(form));
    if (!validators[index](formProps, form)) {
        return;
    }
    showLoading();
    let responsePromise;
    if (index == 3 || index == 4) {
        responsePromise = fetch(form.action, {
            method: 'POST', body: new FormData(form)
        });
    } else {
        responsePromise = fetch(form.action, {
            method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(formProps)
        });
    }
    responsePromise
        .then(response => response.json())
        .then(data => {
            console.log(data);
            if (data.success !== true) {
                if (data.message !== null) {
                    showPrompt('请求失败：' + data.message);
                } else {
                    showPrompt('请求失败，请重试!');
                }
                hideLoading();
                return;
            }
            callback(data.data, index);
        })
        .catch(error => {
            console.log(error);
            showPrompt('请求失败，请重试!');
            hideLoading();
        });
}

function changeType(type) {
    if (type == 2) {
        clearCanvas();
    }
    Array.from(document.getElementsByClassName('type-btn')).forEach((item, index) => {
        if (index === (type - 1)) {
            item.classList.add('btn-primary')
            item.classList.remove('btn-outline-primary')
        } else {
            item.classList.add('btn-outline-primary')
            item.classList.remove('btn-primary')
        }
    })
    for (let i = 1; i <= document.forms.length; i++) {
        document.getElementById('form-' + i).style.display = (i == type ? '' : 'none');
    }
}

function clearCanvas() {
    var canvas = document.getElementById('drawingCanvas');
    var ctx = canvas.getContext('2d');
    // 清除整个画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 首先填充一个白色的背景
    ctx.fillStyle = '#ffffff'; // 设置填充颜色为白色
    ctx.fillRect(0, 0, canvas.width, canvas.height); // 填充整个画布
    window.blankCanvasData = canvas.toDataURL();
}

document.addEventListener('DOMContentLoaded', function () {
    // 关闭模态框的事件处理
    document.getElementById('closeModal').addEventListener('click', function () {
        document.getElementById('imageModal').style.display = 'none';
    });

    var canvas = document.getElementById('drawingCanvas');
    var ctx = canvas.getContext('2d');
    var painting = false;

    function startPaint(e) {
        painting = true;
        paint(e);
    }

    function endPaint() {
        painting = false;
        ctx.beginPath(); // 开始一条新路径，防止线条连接在一起
    }

    function paint(e) {
        if (!painting) return;

        ctx.lineWidth = 3; // 设置线条宽度
        ctx.lineCap = 'round'; // 设置线条末端样式为圆形
        ctx.strokeStyle = 'black'; // 设置线条颜色

        var rect = canvas.getBoundingClientRect();
        var scaleX = canvas.width / rect.width; // canvas的实际宽度和CSS宽度之比
        var scaleY = canvas.height / rect.height; // canvas的实际高度和CSS高度之比
        // 使用比例因子来调整鼠标的x和y坐标
        var x = (e.clientX - rect.left) * scaleX;
        var y = (e.clientY - rect.top) * scaleY;
        ctx.lineTo(x, y); // 画线到当前鼠标位置
        ctx.stroke();
        ctx.beginPath(); // 开始一条新路径
        ctx.moveTo(x, y); // 将路径起点移动到鼠标位置
    }

    // 监听 `mousedown` 事件以开始绘画
    canvas.addEventListener('mousedown', startPaint);

    // 监听 `mousemove` 事件以绘制涂鸦
    canvas.addEventListener('mousemove', paint);

    // 在用户释放鼠标或退出Canvas元素时停止绘画
    canvas.addEventListener('mouseup', endPaint);
    canvas.addEventListener('mouseleave', endPaint);
});

function convertCanvasToImage() {
    var canvas = document.getElementById('drawingCanvas');
    // 获取canvas内容的数据URL
    var imageUrl = canvas.toDataURL("image/png");

    // 创建一个链接元素，下载图片
    var downloadLink = document.createElement('a');
    downloadLink.href = imageUrl;
    downloadLink.download = 'canvas_image.png';

    // 触发链接的点击事件来下载图片
    downloadLink.click();
}

// 显示loading弹出框
function showLoading() {
    document.getElementById('loadingModal').style.display = 'flex';
}

// 隐藏loading弹出框
function hideLoading() {
    document.getElementById('loadingModal').style.display = 'none';
}

function styleChange(value) {
    if (['portrait_url_template', 'train_free_portrait_url_template'].includes(value)) {
        document.getElementById('sizeTr').style.display = 'none';
        document.getElementById('templateImageTr').style.display = '';
    } else {
        document.getElementById('sizeTr').style.display = '';
        document.getElementById('templateImageTr').style.display = 'none';
    }
    // document.getElementById('user-image-tr').style.display = (value == 'portrait_url_template') ? '' : 'none';
}

function addUserImage() {
    let container = document.getElementById('user-image-container');
    if (container.childElementCount >= 5) {
        showPrompt('最多5张图片！');
        return;
    }
    let li = document.createElement('li');

    let input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/jpeg, image/png, image/jpg';
    input.name = 'userImageList';
    li.appendChild(input);
    container.appendChild(li);
}

function text2img() {
    document.getElementById("text2img_prompt").value = "少女，高分辦率，增加细节，细节强化，侧面视角，森林，奶油风，暖色调，精致的脸部比例，精细的裙子，五官立体，长卷发，极高分辨率，清晰度强化，全身像，微笑，五颜六色的花瓣飞舞，自然光";
    document.getElementById("text2img_negativePrompt").value = "低质量，模糊，蓝色眼睛，胡子";
}

function clearText2img() {
    document.getElementById("text2img_prompt").value = "";
    document.getElementById("text2img_negativePrompt").value = "";
}

